package tech.aichan.AiQA.exception;

import cn.hutool.http.HttpStatus;
import jakarta.annotation.PostConstruct;
import tech.aichan.AiQA.common.BaseResponse;
import tech.aichan.AiQA.constant.SecurityConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * @author mengyu
 * @date 2024/03/03 9:26
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @PostConstruct
    void test(){
        log.error("GlobalExceptionHandler build");
    }

    @ExceptionHandler(BusinessException.class)
    public BaseResponse<?> businessExceptionHandler(BusinessException e) {
        log.error("BusinessException : {}", e.getMessage());
        return BaseResponse.error(e.getCode(),e.getMessage());
    }

//    @ExceptionHandler(RuntimeException.class)
//    public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
//        log.error("RuntimeException : {}", e.getMessage());
//        return BaseResponse.error(50000,"系统错误:"+e.getMessage());
//    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResponse<?> validExceptionHandler(MethodArgumentNotValidException e){
        log.error("ConstraintViolationException : {}",e.getMessage());
        String defaultMessage = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        return BaseResponse.error(HttpStatus.HTTP_FORBIDDEN,defaultMessage);
    }

    @ExceptionHandler(AuthenticationException.class)
    public BaseResponse<?> AuthenticationExceptionHandler(AuthenticationException e){
        log.error("AuthenticationException :{}",e.getMessage());
        return BaseResponse.error(HttpStatus.HTTP_FORBIDDEN, SecurityConstant.LOGIN_FAILED);
    }

    @ExceptionHandler(AccessDeniedException.class)
    public BaseResponse<?> AccessDeniedExceptionHandler(AccessDeniedException e){
        log.error("AccessDeniedException :{}",e.getMessage());
        return BaseResponse.error(HttpStatus.HTTP_FORBIDDEN, SecurityConstant.ACCESS_DENIED);
    }
}
